<?php

namespace api\modules\backend\controllers;

use yii;
use yii\filters\auth\QueryParamAuth;
use yii\data\Pagination;
use common\commands\VtCommon;

/**
 * Member Controller API
 *
 * @author Fong <xiaofeng.zhang>
 */
class MemberController extends ControllerBase
{
    public $modelClass = 'api\modules\backend\models\Member';
    public $memberDelete = 0;
    public $memberStatus = 1;
    public $pagination = ['total' => 0, 'pageSize' => 1, 'current' => 1];
    public $filter = ['username' => '', 'phone' => '', 'updatedAt' => '', 'status' => ''];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className(),
            'optional' => [],
        ];
        $behaviors['authenticator']['except'] = ['options'];
        return $behaviors;
    }

    /**
     * 会员列表
     */
    public function actionIndex($currentPage = 1, $pageSize = 20)
    {
        $memberModelClass = $this->modelClass;

        $page = Yii::$app->request->get('currentPage', $currentPage);
        $pageSize = Yii::$app->request->get('pageSize', $pageSize);

        $memberCondition = [];

        $memberStatusCount = explode(',', Yii::$app->request->get('status'));
        if (!is_null(Yii::$app->request->get('status')) && count($memberStatusCount) === 1) $memberCondition['status'] = Yii::$app->request->get('status');
        if (!is_null(Yii::$app->request->get('username'))) $memberCondition['username'] = Yii::$app->request->get('username');
        if (!is_null(Yii::$app->request->get('phone'))) $memberCondition['phone'] = Yii::$app->request->get('phone');

        $memberUpdateAt = Yii::$app->request->get('updatedAt');
        $memberUpdateAtStart = strtotime(date('Y-m-d 00:00:00', $memberUpdateAt));
        $memberUpdateAtEnd = strtotime(date('Y-m-d 23:59:59', $memberUpdateAt));
        $memberDateCondition = !is_null(Yii::$app->request->get('updatedAt')) ? ['between', 'update_time', $memberUpdateAtStart, $memberUpdateAtEnd] : [];

        $memberUpdateAtSort = !is_null(Yii::$app->request->get('sorter')) && Yii::$app->request->get('sorter') === 'createdAt_descend' ? 'update_time DESC' : 'update_time ASC';

        $memberFields = array(
            'key' => 'id',
            'avatar',
            'username',
            'phone',
            'status',
            'createdAt' => 'from_unixtime(create_time, \'%Y-%m-%d %H:%i:%s\')',
            'disabled' => 'status'
        );
        $query = $memberModelClass::find()->from('{{%member}}')->select($memberFields)
            ->where(['is_delete' => $this->memberDelete])
            ->andWhere($memberCondition)
            ->andFilterWhere($memberDateCondition)
            ->orderBy($memberUpdateAtSort);

        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => $pageSize, 'page' => $page - 1]);

        $memberList = $query->offset($pages->offset)
            ->limit($pages->limit)
            ->asArray()
            ->all();

        $memberPagination = array(
            'total' => intval($pages->totalCount),
            'pageSize' => $pages->getPageSize(),
            'current' => $pages->getPage() + 1
        );

        $result = array('list' => $memberList, 'pagination' => $memberPagination);
        $this->success($result);
    }

    /**
     * 删除会员
     * @throws yii\db\Exception
     */
    public function actionDelete()
    {
        $currentPage = !empty(Yii::$app->request->get('currentPage')) ? Yii::$app->request->get('currentPage') : 1;
        $pageSize = !empty(Yii::$app->request->get('pageSize')) ? Yii::$app->request->get('pageSize') : 20;

        $idStr = Yii::$app->request->get('id') ? Yii::$app->request->get('id') : Yii::$app->request->post('id');
        $ids = explode(',', $idStr);

        $value = [];
        foreach ($ids as $id) {
            $value[] = [1, time()];
        }

        if (!empty($ids)) {
            Yii::$app->db->createCommand()
                ->batchUpdate('{{%member}}', ['is_delete', 'update_time'], $value, $ids, 'id')
                ->execute();
        }

        self::actionIndex();
    }

    /**
     * @throws yii\db\Exception
     */
    public function actionDisabled()
    {
        $pagination = Yii::$app->request->post('pagination', $this->pagination);
        $ids = !empty(Yii::$app->request->post('ids')) ? explode(',', Yii::$app->request->post('ids')) : [];

        if (!empty($ids)) {
            $value = [];
            for ($i = 0; $i < count($ids); $i++) {
                $value[] = [0, time()];
            }

            Yii::$app->db->createCommand()
                ->batchUpdate('{{%member}}', ['status', 'update_time'], $value, $ids, 'id')
                ->execute();
        }

        self::actionIndex($pagination['current'], $pagination['pageSize']);
    }

    /**
     * 批量操作
     * @throws yii\db\Exception
     */
    public function actionBatch()
    {
        $method = Yii::$app->request->post('method');

        switch ($method) {
            case 'delete':
                self::actionDelete();
                break;
            case 'disabled':
                self::actionDisabled();
                break;
            default:
                $this->response(VtCommon::getPackedResponse(DATABASE_FAILED, Yii::t('app', 'DATABASE_FAILED'), null));
        }
    }
}